from flask import Flask , request,session,redirect,render_template
from flask import render_template
from research import reserch4letters
from data import data
# 服务端的中央登记中心
# 1.URL：*URL的相对路径（终结点）*request的methods【get】【post】
# 2.view function：视图函数，*模板渲染【HTML+CSS】*，处理数据
# 3.return：返回到templates文件夹中对应的HTML文件


app = Flask(__name__)

# 1. 登记路由： route
@app.route('/',methods=['GET','POST']) # / 根路径，首页, 相对路径
# 2. 视图函数，返回值为页面的显示信息，文本txt，html，json等
def hello():
    return render_template('hello.html')

# 练习：尝试写一个界面 路由为 /index， 视图函数返回的内容为 <h1>这是首页</h1>
@app.route('/index',methods=['GET','POST'])
def index():
    return render_template('index.html')

@app.route('/result',methods=['POST'])
def result():
    # 用户输入的信息是在 request中的
    first_name = request.form['firstname']
    last_name = request.form['lastname']
    full_name = first_name.title() + ' ' + last_name.title()

    py_word = request.form['word']
    py_vowels = request.form['vowels']
    py_found = reserch4letters(py_vowels, py_word)

    return render_template('result.html',
                           fullname=full_name,
                           found = py_found)

cartList = []

# 路由：返回'商品'页面
@app.route('/goods')
def goods():
    # 从session中获取money
    money = session.get('money')
    return render_template('goods.html', goods_list = data.goods_list, total_money=money)

# 路由：返回'购物车'页面
@app.route('/cart', methods=['GET'])
def cart():
    # 有两个入口进购物车，这里指的是点击商品加入购物车
    if request.args.get('_id'):
        # 当前物品
        curGood = {}
        for i in data.goods_list:
            if i['_id'] == request.args.get('_id'):
                curGood = i
        if curGood not in cartList:
            cartList.append(curGood)
    return render_template('cart.html', cart_list = cartList)

# 路由：结算（购物车中的全部物品）
@app.route('/shop')
def shop():
    # 页面文字
    msg = ''
    # 剩余费用
    left_money = 0
    # 计算总费用
    sum = 0
    for i in cartList:
        sum = sum + i['price']
    if session.get('money') == None:
        msg = '请在商品页面填写账户余额~'
    else:
        if sum > session.get('money'):
            msg = '余额不足，请充值~'
        else:
            msg = '购买成功，静待发货~'
            left_money = session.get('money') - sum
            # 将最新余额更新到session
            session['money'] = left_money
    return render_template('pay.html', msg=msg, left_money=left_money)

# 路由：购买单个物品页面
@app.route('/buy', methods=['GET'])
def buy():
    # 当前物品
    curGood = {}
    for i in data.goods_list:
        if i['_id'] == request.args.get('_id'):
            curGood = i
    return render_template('buy.html', cur_good = curGood)


# 路由：结算（单个物品）
@app.route('/buy_single')
def buy_single():
    # 页面文字
    msg = ''
    # 剩余费用
    left_money = 0
    # 单个物品费用
    price = 0
    for i in data.goods_list:
        if i['_id'] == request.args.get('_id'):
            price = i['price']
    if session.get('money') == None:
        msg = '请在商品页面填写账户余额~'
    else:
        if price > session.get('money'):
            msg = '余额不足，请充值~'
        else:
            msg = '购买成功，静待发货~'
            left_money = session.get('money') - price
            # 将最新余额更新到session
            session['money'] = left_money
    return render_template('pay.html', msg=msg, left_money=left_money)

# 路由：处理金额，存入session中
@app.route('/submit/money')
def submit_money():
    # 将金额存入session中，便于全局取用
    money = request.args.get('money')
    session['money'] = int(money)
    return redirect('/goods')


if __name__ == '__main__':
    app.run(host='127.0.0.1',port=5000,debug=True)
